package com.wjs.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share{
    private int num =0;
    private Lock lock=new ReentrantLock();
    private Condition condition = lock.newCondition();
    public void incr() throws InterruptedException {
        lock.lock();
        try {
            while (num!=0){
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"::"+num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
    public void dncr() throws InterruptedException {
        lock.lock();
        try {
            while (num!=1){
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"::"+num);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}
public class ThreadDemo {
    public static void main(String[] args) {
        Share share = new Share();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"aa").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.dncr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"bb").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.incr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"cc").start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
                    share.dncr();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"dd").start();
    }
}
